import { Page } from './ix';
import CryptoJS from './CryptoJS.js';

Page({
  data: {
    fee: '',
    shopname: my.getStorageSync({ key: 'shopname' }).data,
    background:['/image/1.jpg','/image/2.jpg','/image/3.jpg','/image/4.jpg']
  },
  onLoad(query) {
    // 页面加载
    my.getServerTime({
      success: (res) => {
        this.setData({ time: res.time });
      },
    });
    my.ix.startMonitorPrinter({
      success: (r) => {
        console.log("success");
      },
      fail: (r) => {
        console.log("fail, errorCode:" + r.error);
      }
    });
    my.ix.queryPrinter({
      success: (r) => {
        this.setData({
          message: JSON.stringify(r)
        })
      },
      fail: (r) => {
        this.setData({
          message: JSON.stringify(r)
        })
      }
    });


  },
  onReady() {
    // 页面加载完成
  },
  onShow() {
    // 页面显示
    my.getServerTime({
      success: (res) => {
        this.setData({ time: res.time });
      },
    });
  },
  onHide() {
    // 页面隐藏
  },
  scan() {
    if (this.data.fee) {
      if (this.data.fee <= 0) {
        my.alert({
          title: '金额错误'
        });
      } else {
        this.face();
      }
    } else {
      my.alert({
        title: '请输入金额'
      });
    }
  },
  face() {
    if (this.data.fee <= 0) {
      my.alert({
        title: '金额错误'
      });
    } else {
      my.ix.startApp({
        appName: 'cashier',
        bizNo: my.getStorageSync({ key: 'nohead' }).data + this.data.time,
        faceLoadingTimeout: 5,
        showScanPayResult: true,
        success: (r) => {
          if (r.barCode.substr(0, 1) == "1") {
            my.setStorage({
              key: 'pay_mch_key',
              data: { 'pay_platform': 1, 'out_mch_id': 'sz01RArHTeMtZSoLbDeG', 'out_sub_mch_id': my.getStorageSync({ key: 'pay_mch_key' }).data.out_sub_mch_id, 'out_shop_id': my.getStorageSync({ key: 'pay_mch_key' }).data.out_shop_id, },
            });
            this.setData({
              paytype: '微信',
            });
          } else {
            my.setStorage({
              key: 'pay_mch_key',
              data: { 'pay_platform': 2, 'out_mch_id': 'sz01RArHTeMtZSoLbDeG', 'out_sub_mch_id': my.getStorageSync({ key: 'pay_mch_key' }).data.out_sub_mch_id, 'out_shop_id': my.getStorageSync({ key: 'pay_mch_key' }).data.out_shop_id, },
            });
            this.setData({
              paytype: '支付宝',
            });
          }
          this.setData({
            request_content: JSON.stringify({
              pay_mch_key: my.getStorageSync({ key: 'pay_mch_key' }).data,
              nonce_str: this.randomString(),
              order_client: {
                device_id: my.getStorageSync({ key: 'device_id' }).data,
                terminal_type: 100,
                machine_no: my.getStorageSync({ key: 'device_id' }).data,
                sdk_version: '1.6',
                spbill_create_ip: '90.0.0.0',
              },
              pay_content: {
                total_fee: this.data.fee * 100,
                author_code: r.barCode,
                out_trade_no: my.getStorageSync({ key: 'nohead' }).data + this.data.time,
                fee_type: 'CNY',
                body: '景轩独立收银支付'
              },
            }),
          });
          this.setData({
            requestdata: {
              authen_info: {
                a: {
                  authen_type: 1,
                  authen_code: CryptoJS.HmacSHA256(this.data.request_content, my.getStorageSync({ key: 'key' }).data).toString().toUpperCase()
                }
              },
              request_content: this.data.request_content
            }
          });
          console.log('msg:' + JSON.stringify(this.data.requestdata));
          my.request({
            url: 'https://pay.qcloud.com/cpay/micro_pay',
            // url: 'localhost/index.php/micro_pay',
            method: 'POST',
            data: this.data.requestdata,
            dataType: 'json',
            success: (res) => {
              console.log('ok:' + JSON.stringify(res.data));
              my.getServerTime({
                success: (res) => {
                  this.setData({ time: res.time });
                },
              });
              if (res.data.response_content) {
                var response_content = JSON.parse(res.data.response_content);
                if (response_content.status == 0) {
                  my.showToast({
                    type: 'success',
                    content: '支付成功',
                    duration: 3000,
                  });
                  my.ix.printer({
                    cmds: [{ 'cmd': 'addCutAndFeedPaper', 'args': ['10'] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'ON'] },
                    { 'cmd': 'addSelectJustification', 'args': ['CENTER'] },
                    { 'cmd': 'addText', 'args': [this.data.shopname] },
                    { 'cmd': 'addPrintAndLineFeed', 'args': [] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': ['订单号:'] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': [response_content.micro_pay.order_content.out_trade_no] },
                    { 'cmd': 'addPrintAndLineFeed', 'args': [] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': ['订单总金额:'] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': [response_content.micro_pay.order_content.total_fee * 0.01] },
                    { 'cmd': 'addPrintAndLineFeed', 'args': [] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': ['实际支付:'] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': [response_content.micro_pay.order_content.cash_fee * 0.01] },
                    { 'cmd': 'addPrintAndLineFeed', 'args': [] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': ['第三方支付类型:'] },
                    { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
                    { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
                    { 'cmd': 'addText', 'args': [this.data.paytype] },
                    { 'cmd': 'addPrintAndLineFeed', 'args': [] },
                    { 'cmd': 'addSelectJustification', 'args': ['CENTER'] }, /*设置打印居中对齐*/
                    { 'cmd': 'addSelectErrorCorrectionLevelForQRCode', 'args': ['49'] }, /*设置纠错等级*/
                    { 'cmd': 'addSelectSizeOfModuleForQRCode', 'args': ['10'] }, /*设置qrcode模块大小*/
                    { 'cmd': 'addStoreQRCodeData', 'args': [response_content.micro_pay.order_content.out_trade_no] }, /*设置qrcode内容*/
                    { 'cmd': 'addPrintQRCode', 'args': [] }, /*打印QRCode*/
                    { 'cmd': 'addPrintAndLineFeed', 'args': [] }],
                    success: (r) => {
                      console.log("success");
                    },
                    fail: (r) => {
                      console.log("fail, errorCode:" + r.error);
                    }
                  });
                  my.ix.startApp({
                    appName: 'scanPayResult',
                    bizNo: my.getStorageSync({ key: 'nohead' }).data + this.data.time,
                    totalAmount: response_content.micro_pay.order_content.cash_fee,
                    bizAmount: response_content.micro_pay.order_content.total_fee,
                    discount: response_content.micro_pay.order_content.total_fee - response_content.micro_pay.order_content.cash_fee,
                    success: (r) => {
                      my.showToast({ content: JSON.stringify(r) });
                    },
                    fail: (r) => {
                      console.log('scanPayResultfail:' + JSON.stringify(r));
                    }
                  });
                } else {
                  my.showToast({
                    type: 'success',
                    content: response_content.description,
                    duration: 3000,
                  });
                }
              }
            },
            fail: (res) => {
              console.log('fail:' + JSON.stringify(res));
              my.alert({
                title: '支付请求失败'
              });
            },
          });
        },
        fail: (r) => {
          console.log('cashierfail:' + JSON.stringify(r));
        }
      });
    }
  },
  authorize() {

  },
  setfee(e) {
    this.setData({
      fee: e.detail.value,
    });
  },
  onKeyPress(r) {
    this.setData({ fee: r.amount });
    switch (r.keyCode) {
      case 131:
        r.keyName = '收款';
        this.scan();
        break;
      case 132:
        r.keyName = '刷脸';
        break;
      case 133:
        r.keyName = '取消';
        break;
      case 134:
        r.keyName = '设置';
        my.navigateTo({ url: '../center/center' });
        break;
    }
    console.log('KeyEvent', r);
  },
  randomString() {
    var len = 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },
});
